package cn.jiedanba.cacert.ocspserver.controller;

import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import cn.jiedanba.cacert.common.result.ResponseResult;
import cn.jiedanba.cacert.ocspserver.service.OcspService;

@RestController
public class OcspController {

	@Autowired
	private OcspService ocspService;

	/**
	 * 证书状态查询
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/")
	public void ocspQuery(HttpServletRequest request, HttpServletResponse response) throws IOException {

		if (!request.getMethod().equalsIgnoreCase("POST")) {
			response.sendError(400);
			return;
		}

		if (request.getContentType() == null || !request.getContentType().equals("application/ocsp-request")) {
			response.sendError(400);
			return;
		}
		int len = request.getContentLength();
		if (len < 1 || len > 100000) {
			response.sendError(400);
			return;
		}
		byte[] bytes = IOUtils.toByteArray(request.getInputStream());
		ResponseResult rr = ocspService.ocspQuery(bytes);
		if (!rr.isSuccess()) {
			response.setContentType("application/json; charset=UTF-8");
			response.getOutputStream().write(JSON.toJSONString(rr).getBytes());
			return;
		}
		byte[] ocspResponse = (byte[]) rr.getData();

		response.setContentType("application/ocsp-response");
		response.setHeader("Connection", "close");
		response.setHeader("content-encoding", "binary");
		response.setContentLength(ocspResponse.length);
		ServletOutputStream so = response.getOutputStream();
		so.write(ocspResponse);
	}

}
